<script setup name="verification">
import Material from '@/components/XiaoheComponents/material'
import Buttons from '@/components/XiaoheComponents/XiaoheButton'
import { GetMenuPermAPI } from '@/api/system/billconfig'
import { GetListAPI, AddDataAPI, EditDataAPI, DelDataAPI } from '@/api/system/verification'
import { Search } from '@element-plus/icons-vue'
import { get } from '@vueuse/core'
const { proxy } = getCurrentInstance()
const {
  sys_check_segment, // 编码校验码段
  sys_coding_rules, // 编码规则
  sys_configuration_type // 编码校验配置类型
} = proxy.useDict('sys_check_segment', 'sys_configuration_type', 'sys_coding_rules')

// 表单ref
const ruleFormRef = ref(null)

// 单据配置数据
const menuOptions = ref([])
// 弹窗title
const title = ref('新增')
// 选中ID
const Ids = ref([])

// 是否禁用修改按钮
const Single = ref(false)

// 是否禁用删除按钮
const Multiple = ref(false)

// 列表数据
const TableData = ref([])

// 列表总数量
const total = ref(0)

// 列表加载
const loading = ref(false)

const TableForm = ref([])

// 保存按钮加载
const BtnLoading = ref(false)

// 信息展示状态
const Drawer = ref(false)

/**
 * 弹窗状态
 */

// 新增
const dialogVisible = ref(false)

// 物料选择弹窗
const materialIsShow = ref(false)

// 供应商弹窗
const SupplierIsShow = ref(false)

// 客户弹窗
const CustomerIsShow = ref(false)

// 单据选择弹窗
const BillIsShow = ref(false)

const FormTebls = ref([])

// 查询条件
const query = reactive({
  pageNum: 1,
  pageSize: 10,
  verType: '',
  verTheRules: '',
  verDocumentsCode: '',
  selectTime: ''
})

// 按钮枚举数据
const ButtonList = ref([
  { type: 'add', hasPermi: 'system:verification:add' },
  { type: 'remove', hasPermi: 'system:verification:remove', disabled: Multiple }
])
/**
 * 查询枚举
 */
const SelectList = ref([
  { label: '', type: '日期范围' },
  { label: '配置类型', model: 'verType', type: '下拉单选', opt: sys_configuration_type },
  { label: '规则名称', model: 'verTheName', type: '输入框', placeholder: '请输入规则名称' },
  { label: '单据名称', model: 'verDocumentsCodeName', type: '输入框', placeholder: '请输入单据名称' },
  { label: '物料名称', model: 'verItemName', type: '输入框', placeholder: '请输入物料名称' }
])

// 列表选中 及 判断是否禁用删除 || 修改
const handleSelectionChange = selection => {
  Ids.value = selection.map(item => item.verId)
  Single.value = selection.length != 1
  Multiple.value = !selection.length
}
handleSelectionChange([])

// 表格表单
const ruleForm = reactive({
  verItemCode: '', // 物料编码
  materialName: '', // 物料名称
  materialSpec: '', // 物料规格
  verType: '', // 配置类型
  verTheRules: '', // 规则编码
  verTheName: '', // 规则名称
  verDocumentsCode: '', // 单据名称
  verCustomCode: '', //  客户编码
  verCustomName: '', // 客户名称
  verSupplierCode: '', // 供应商编码
  verSupplierName: '', //  供应商名称
  sysVerificationDetailedList: []
})
// 表格表单校验
const rules = reactive({
  materialName: [{ required: true, message: '请选择物料编码', trigger: 'change' }],
  verType: [{ required: true, message: '请选择配置类型', trigger: 'change' }],
  verTheRules: [
    { required: true, message: '请填写规则编码', trigger: 'blur' },
    { validator: proxy.noChinese, trigger: 'blur' }
  ],
  verTheName: [{ required: true, message: '请填写规则名称', trigger: 'blur' }],
  verCustomName: [{ required: true, message: '请选择供应商', trigger: 'change' }],
  verSupplierName: [{ required: true, message: '请选择客户', trigger: 'change' }]
})

// 码段添加
const AddTypeFn = () => {
  // 1 日期变量 2 流水号 3 本文
  ruleForm.sysVerificationDetailedList.push({
    detContent: null, // 码段
    detSegment: null, // 变量
    detTheLength: null, // 长度
    detTheRules: null
  })
}
const FormTeblChange = row => {
  FormTebls.value = row
}

// 删除表格表单
const RemoveTypeFn = scope => {
  if (FormTebls.value.length > 0) {
    FormTebls.value.forEach(item => {
      const Find = ruleForm.sysVerificationDetailedList.findIndex(itemy => item.infoId == itemy.infoId)
      ruleForm.sysVerificationDetailedList.splice(Find, 1)
    })
  } else {
    ruleForm.sysVerificationDetailedList.splice(scope.$index, 1)
  }
}
// 表格表单排序 向上
const Up = scope => {
  window.localStorage.setItem('as', JSON.stringify(scope.row))
  if (scope.$index >= 1) {
    const Obj = JSON.parse(window.localStorage.getItem('as'))
    ruleForm.sysVerificationDetailedList.splice(scope.$index - 1, 0, Obj)
    ruleForm.sysVerificationDetailedList.splice(scope.$index + 1, 1)
  } else {
  }
}

// 表格表单排序 向下
const Downward = scope => {
  if (scope.$index != ruleForm.sysVerificationDetailedList.length - 1) {
    window.localStorage.setItem('as', JSON.stringify(scope.row))
    const Obj = JSON.parse(window.localStorage.getItem('as'))
    ruleForm.sysVerificationDetailedList.splice(scope.$index + 2, 0, Obj)
    ruleForm.sysVerificationDetailedList.splice(scope.$index, 1)
  } else {
  }
}

// 新增
const addDialog = () => {
  title.value = '新增'
  dialogVisible.value = true
}

// 修改
const edit = val => {
  title.value = '修改'
  for (let KEY in val) {
    ruleForm[KEY] = val[KEY]
  }
  console.log(val.verDocumentsCodes1.split(','))
  ruleForm.verDocumentsCodes = val.verDocumentsCodes1.split(',').map(item => Number(item))
  ruleForm.verType = String(ruleForm.verType)
  // console.log(val)
  // ruleForm.sysVerificationDetailedList=[]
  dialogVisible.value = true
}

// 查看
const look = val => {
  title.value = '查看'
  for (let KEY in val) {
    ruleForm[KEY] = val[KEY]
  }
  ruleForm.verType = String(ruleForm.verType)

  ruleForm.verDocumentsCodes = val.verDocumentsCodes1.split(',').map(item => Number(item))
  // ruleForm.sysVerificationDetailedList=[]
  dialogVisible.value = true
}

// 新增提交
const addSub = async () => {
  const valid = await ruleFormRef.value.validate()
  if (!valid) return
  const arr = ruleForm.sysVerificationDetailedList
  if (arr.length < 1) return proxy.warningMsg('至少添加一条明细项')
  const ifis = arr.every(item => item.detTheRules && item.detTheLength && item.detContent && item.detSegment)
  if (!ifis) return proxy.warningMsg('请填写一条完整明细项')
  try {
    BtnLoading.value = true
    AddDataAPI(ruleForm)
    cancel()
    getList()
    proxy.successMsg('新增成功')
  } catch {
  } finally {
    BtnLoading.value = false
  }
}

// 修改提交
const editSub = async () => {
  const valid = await ruleFormRef.value.validate()
  if (!valid) return
  const arr = ruleForm.sysVerificationDetailedList
  if (arr.length < 1) return proxy.warningMsg('至少添加一条明细项')
  const ifis = arr.every(item => item.detTheRules && item.detTheLength && item.detContent && item.detSegment)
  if (!ifis) return proxy.warningMsg('请填写一条完整明细项')
  try {
    BtnLoading.value = true
    EditDataAPI(ruleForm)
    cancel()
    getList()
    proxy.successMsg('修改成功')
  } catch (err) {
    // console.log(err)
  } finally {
    BtnLoading.value = false
  }
}

// 删除
const del = async id => {
  const MesBox = await proxy.DelMessageBox()
  if (!MesBox) return
  const res = await DelDataAPI(id ? id : Ids.value.join(','))
  if (res.code !== 200) return
  proxy.successMsg('删除成功')
  getList()
}

const TableSelectFn = val => {
  // console.log(val)
}

/**
 * 弹窗取消后
 */

// 新增
const close = () => {
  dialogVisible.value = false
}

// 弹窗 关闭
const cancel = () => {
  for (let KEY in ruleForm) {
    ruleForm[KEY] = ''
  }
  ruleForm.sysVerificationDetailedList = []
  materialIsShow.value = false
  dialogVisible.value = false

  SupplierIsShow.value = false
  CustomerIsShow.value = false
}

// 选择客户
const preservation = val => {
  // console.log(val, '客户')
  ruleForm.verCustomName = val.customerName
  ruleForm.verCustomCode = val.customerNum
  CustomerIsShow.value = false
}

// 供应商选择
const supplierSub = val => {
  ruleForm.verSupplierName = val.supplierName
  ruleForm.verSupplierCode = val.supplierNum
  SupplierIsShow.value = false
}

// 选择物料
const materialSub = val => {
  ruleForm.verItemName = val.materialName
  ruleForm.verItemCode = val.materialCode
  ruleForm.materialSpec = val.materialSpec
  materialIsShow.value = false
}

// 选择单据
const nodeClick = async val => {
  const id = val[val.length - 1]
  ruleForm.verDocumentsCode = id
}

/** 查询列表 */
const getList = async () => {
  try {
    loading.value = true
    const res = await GetListAPI(query)
    total.value = res.total
    TableData.value = res.rows
  } catch {
  } finally {
    loading.value = false
  }
}

// 查询按钮
const selectSubmit = val => {
  for (let KEY in val) {
    query[KEY] = val[KEY]
  }
  getList()
}
getList()
/** 查询菜单树结构 */
function getMenuTreeselect() {
  GetMenuPermAPI().then(response => {
    menuOptions.value = response.data
  })
}
getMenuTreeselect()
</script>
<template>
  <div class="app-container">
    <!-- 查询条件组件 -->
    <SelectForm :SelectForm="SelectList" @selectSubmit="selectSubmit" />
    <el-card class="box-card">
      <!-- 按钮组件 -->
      <el-button type="primary" @click="addDialog" v-hasPermi="['system:verification:add']">新增</el-button>
      <el-button type="danger" :disabled="Multiple" @click="del(false)" v-hasPermi="['system:verification:remove']"
        >删除</el-button
      >
      <!-- 表格数据 -->
      <el-table
        style="margin-top: 15px"
        v-loading="loading"
        stripe
        border
        :data="TableData"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" fixed="left" />
        <el-table-column label="序号" type="index" width="80" />
        <el-table-column label="配置类型" prop="verTypeDict" width="auto" />
        <el-table-column label="规则编码" prop="verTheRules" width="200" />
        <el-table-column label="规则名称" prop="verTheName" :show-overflow-tooltip="true" width="auto" />
        <el-table-column label="单据名称" prop="verDocumentsCodeName" width="180" :show-overflow-tooltip="true" />
        <el-table-column
          label="物料名称"
          align="center"
          prop="verItemName"
          width="auto"
          :show-overflow-tooltip="true"
        />
        <el-table-column label="创建人" align="center" prop="createBy" width="auto" :show-overflow-tooltip="true" />
        <el-table-column label="创建时间" align="center" prop="createTime" width="auto" :show-overflow-tooltip="true" />
        <el-table-column label="操作" align="center" width="220" class-name="small-padding fixed-width">
          <template #default="scope">
            <div>
              <el-link type="primary" @click="edit(scope.row)" v-hasPermi="['system:verification:edit']">修改</el-link>
              <el-link type="primary" @click="del(scope.row.verId)" v-hasPermi="['system:verification:remove']"
                >删除</el-link
              >
              <el-link type="primary" @click="look(scope.row)" v-hasPermi="['system:verification:query']">查看</el-link>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <pagination
          v-show="total > 0"
          :total="total"
          v-model:page="query.pageNum"
          v-model:limit="query.pageSize"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 新增弹窗 -->
    <p-XiaoheDialog :dialogVisible="dialogVisible" :title="title" @close="cancel">
      <template #body>
        <el-form ref="ruleFormRef" :inline="true" :model="ruleForm" :rules="rules" label-width="100px">
          <el-form-item label="配置类型" prop="verType">
            <el-select v-model="ruleForm.verType" placeholder="请选择配置类型" :disabled="title == '查看'">
              <el-option
                v-for="(item, index) in sys_configuration_type"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="规则名称" prop="verTheName">
            <el-input
              v-model="ruleForm.verTheName"
              clearable
              placeholder="请输入规则名称"
              :disabled="title == '查看'"
            />
          </el-form-item>
          <el-form-item label="规则编码" prop="verTheRules">
            <el-input
              v-model="ruleForm.verTheRules"
              clearable
              placeholder="请输入规则编码"
              :disabled="title == '查看'"
            />
          </el-form-item>

          <el-form-item label="物料选择" prop="verItemCode">
            <el-input
              v-model="ruleForm.verItemCode"
              clearable
              :prefix-icon="Search"
              @click="materialIsShow = true"
              :disabled="title == '查看'"
              placeholder="选择物料"
            />
          </el-form-item>

          <el-form-item label="物料名称">
            <el-input v-model="ruleForm.verItemName" clearable disabled placeholder="请输入物料名称" />
          </el-form-item>
          <el-form-item label="物料规格" prop="materialSpec">
            <el-input v-model="ruleForm.materialSpec" clearable disabled placeholder="物料规格" />
          </el-form-item>
          <el-form-item label="供应商">
            <el-input
              v-model="ruleForm.verSupplierName"
              clearable
              :prefix-icon="Search"
              placeholder="供应商"
              :disabled="title == '查看'"
              @click="SupplierIsShow = true"
            />
          </el-form-item>
          <el-form-item label="客户">
            <el-input
              v-model="ruleForm.verCustomName"
              clearable
              :disabled="title == '查看'"
              :prefix-icon="Search"
              @click="CustomerIsShow = true"
              placeholder="选择客户"
            />
          </el-form-item>
          <el-form-item label="单据" prop="region">
            <el-cascader
              v-model="ruleForm.verDocumentsCodes"
              :disabled="title == '查看'"
              :show-all-levels="false"
              :options="menuOptions"
              node-key="menuId"
              :props="{ value: 'menuId', label: 'menuName' }"
              @change="nodeClick"
            />
          </el-form-item>
        </el-form>
        <!-- 表格表单 -->
        <el-card>
          <template #header>
            <div class="card-header">
              <div class="card-header-title">明细项</div>
              <div class="caozuo" v-if="title != '查看'">
                <el-tooltip class="box-item" effect="dark" content="添加" placement="top-start">
                  <el-icon @click="AddTypeFn"><Plus /></el-icon>
                </el-tooltip>
                <div style="margin: 0 10px"></div>
                <el-tooltip class="box-item" effect="dark" content="勾选删除" placement="top-start">
                  <el-icon @click="RemoveTypeFn"><Minus /></el-icon>
                </el-tooltip>
              </div>
            </div>
          </template>
          <el-table
            v-loading="loading"
            stripe
            border
            :data="ruleForm.sysVerificationDetailedList"
            @selection-change="FormTeblChange"
          >
            <el-table-column type="selection" width="55" align="center" fixed="left" />
            <el-table-column label="序号" width="80" type="index" />

            <el-table-column label="码段" width="220">
              <template #default="scope">
                <el-select
                  :disabled="title == '查看'"
                  v-model="scope.row.detSegment"
                  clearable
                  placeholder="请选择码段"
                >
                  <el-option
                    v-for="(item, index) in sys_check_segment"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="内容" width="auto">
              <template #default="scope">
                <el-input
                  :disabled="title == '查看'"
                  v-model="scope.row.detContent"
                  clearable
                  placeholder="请填写内容"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="长度" width="auto">
              <template #default="scope">
                <el-input
                  :disabled="title == '查看'"
                  type="number"
                  oninput="if(value<=0)value=''"
                  v-model="scope.row.detTheLength"
                  clearable
                  placeholder="请填写长度"
                ></el-input>
              </template>
            </el-table-column>
            <el-table-column label="编码规则" width="auto">
              <template #default="scope">
                <el-select
                  :disabled="title == '查看'"
                  v-model="scope.row.detTheRules"
                  clearable
                  placeholder="请选择编码规则"
                >
                  <el-option
                    v-for="(item, index) in sys_coding_rules"
                    :key="index"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </template>
            </el-table-column>

            <el-table-column label="操作" align="center" width="150" class-name="small-padding fixed-width">
              <template #default="scope">
                <div class="caozuo" v-if="title != '查看'">
                  <el-tooltip class="box-item" effect="dark" content="向上排序" placement="top-start">
                    <el-icon
                      size="30"
                      @click="Up(scope)"
                      v-show="ruleForm.sysVerificationDetailedList.length > 0 && scope.$index !== 0"
                      ><Top
                    /></el-icon>
                  </el-tooltip>
                  <el-tooltip class="box-item" effect="dark" content="向下排序" placement="top-start">
                    <el-icon
                      size="30"
                      @click="Downward(scope)"
                      v-show="
                        ruleForm.sysVerificationDetailedList.length > 1 &&
                        scope.$index != ruleForm.sysVerificationDetailedList.length - 1
                      "
                      ><Bottom
                    /></el-icon>
                  </el-tooltip>
                  <el-tooltip class="box-item" effect="dark" content="删除" placement="top-start">
                    <el-icon size="30" @click="RemoveTypeFn(scope)"><Minus /></el-icon>
                  </el-tooltip>
                </div>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <!-- 按钮 -->
        <div class="Btn" v-if="title != '查看'">
          <div style="flex: 1"></div>
          <div>
            <el-button type="primary" :loading="BtnLoading" @click="title == '新增' ? addSub() : editSub()"
              >保存</el-button
            >
            <el-button @click="dialogVisible = false">取消</el-button>
          </div>
        </div>
      </template>
    </p-XiaoheDialog>
    <!-- 物料选择弹窗 -->
    <Material
      :is-show="materialIsShow"
      :dict="[
        { label: '原料', value: '1' },
        { label: '半成品', value: '3' },
        { label: '辅料', value: '2' },
        { label: '成品', value: '4' }
      ]"
      @cancel="materialIsShow = false"
      @preservation="materialSub"
    />
    <!-- 供应商弹窗 -->
    <Supplier :is-show="SupplierIsShow" @preservation="supplierSub" @cancel="SupplierIsShow = false" />
    <!-- 客户弹窗 -->
    <Customer :is-show="CustomerIsShow" @cancel="CustomerIsShow = false" @preservation="preservation" />
    <!-- 信息展示 -->
    <el-drawer size="50%" v-model="Drawer" title="信息展示">
      <el-form :inline="true">
        <el-form-item label="配置类型:">
          <div class="value">{{ Form.codetypeStr }}</div>
        </el-form-item>
        <el-form-item label="配置编码:">
          <div class="value">{{ Form.verTheRules }}</div>
        </el-form-item>
        <el-form-item label="配置名称:">
          <div class="value">{{ Form.verDocumentsCode }}</div>
        </el-form-item>
      </el-form>
      <el-form>
        <el-form-item label="备注:">
          <div>{{ Form.remark }}</div>
        </el-form-item>
      </el-form>
      <!-- 表格 -->
      <el-table v-loading="loading" stripe border :data="TableForm" @selection-change="handleSelectionChange">
        <el-table-column label="码段" prop="segS" width="auto" />
        <el-table-column label="变量" prop="varS" :show-overflow-tooltip="true" width="auto" />
        <el-table-column label="长度" prop="infoTheLength" :show-overflow-tooltip="true" width="auto" />
        <el-table-column label="填充方式" prop="metS" width="180" />
        <el-table-column label="填充字符" align="center" prop="infoMethodCharacter" width="160" />
        <el-table-column label="起始流水号" align="center" prop="infoTheNumber" width="160" />
      </el-table>
    </el-drawer>
  </div>
</template>
<style scoped>
.my-header {
  width: 200px;
  display: flex;
  flex-direction: row;
  justify-content: space-between;
}
.card-header-title {
  font-weight: 700;
}
.card-header {
  display: flex;
  justify-content: space-between;
}
.Btn {
  margin-top: 10px;
  display: flex;
  justify-content: space-between;
  min-width: 160px;
}
.caozuo {
  display: flex;
  justify-content: space-evenly;
}
.value {
  border-bottom: 1px solid #000;
  width: 120px;
}
.app-container /deep/.el-form-item__content {
  width: 188px !important;
}
</style>
